package com.skyline.user.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.skyline.base.dao.impl.BaseDaoImpl;
import com.skyline.user.dao.EmailTokenDao;
import com.skyline.user.mapper.EmailTokenMapper;
import com.skyline.user.model.EmailToken;
import com.skyline.user.type.EmailTokenType;

@Repository("emailTokenDao")
public class EmailTokenDaoImpl extends BaseDaoImpl implements EmailTokenDao {

	@Value("${EmailTokenDao.queryTokenByEmailAndTypeAndChecked}")
	private String queryTokenByEmailAndTypeAndCheckedSql;

	@Value("${EmailTokenDao.queryTokenByUserIdAndTypeAndChecked}")
	private String queryTokenByUserIdAndTypeAndCheckedSql;
	
	@Value("${EmailTokenDao.queryToken}")
	private String queryTokenSql;

	@Value("${EmailTokenDao.insertToken}")
	private String insertTokenSql;

	@Value("${EmailTokenDao.updateTokenChecked}")
	private String updateTokenCheckedSql;

	@Override
	public List<EmailToken> queryTokenByEmailAndTypeAndChecked(String email, EmailTokenType type, boolean checked) {
		return jdbcTemplate.query(queryTokenByEmailAndTypeAndCheckedSql, EmailTokenMapper.getMapper(),email,  type.toString(),  checked);
	}

	@Override
	public List<EmailToken> queryTokenByUserIdAndTypeAndChecked(long userId, EmailTokenType type, boolean checked) {
		return jdbcTemplate.query(queryTokenByUserIdAndTypeAndCheckedSql, EmailTokenMapper.getMapper(),userId,  type.toString(),  checked);
	}
	
	@Override
	public EmailToken queryToken(String token){
		List<EmailToken> tokens=jdbcTemplate.query(queryTokenSql, EmailTokenMapper.getMapper(),token);
		if(CollectionUtils.isEmpty(tokens)){
			return null;
		}else{
			return tokens.get(0);
		}
	}

	@Override
	public void insertToken(EmailToken token) {
		jdbcTemplate.update(insertTokenSql, token.getUserId(),token.getEmail(),token.getToken(),token.getType().toString(),token.getCheckTime());
	}

	@Override
	public void updateTokenChecked(long id, boolean checked) {
		jdbcTemplate.update(updateTokenCheckedSql,checked,id);
	}

}
